package control

import (
	"lesson01/instructions/base"
	"lesson01/rtda"
)

type TABLE_SWITCH struct {
	defaultOffset int32
	low           int32
	high          int32
	jumpOffsets   []int32
}

func (e *TABLE_SWITCH) FetchOperands(reader *base.BytecodeReader) {
	reader.SkipPadding()
	e.defaultOffset = reader.ReadInt32()
	e.low = reader.ReadInt32()
	e.high = reader.ReadInt32()
	jumpOffsetsCount := e.high - e.low + 1
	e.jumpOffsets = reader.ReadInt32s(jumpOffsetsCount)
}

func (e *TABLE_SWITCH) Execute(frame *rtda.Frame) {
	index := frame.OperandStack().PopInt()

	var offset int
	if index >= e.low && index <= e.high {
		offset = int(e.jumpOffsets[index-e.low])
	} else {
		offset = int(e.defaultOffset)
	}

	base.Branch(frame, offset)
}
